<!--
 * @Description: 周计划节点完成详情
 * @Author: wind-lc
 * @version: 1.0
 * @Date: 2023-03-23 10:46:13
 * @LastEditTime: 2023-04-12 14:28:55
 * @FilePath: \cscec-pms-admin\src\views\construction\weekPlan\components\NodeCompletionView.vue
-->
<template>
  <a-spin :spinning="loading">
    <a-card :class="{'modal': useModal}">
      <custom-form ref="form" :is-validate="true" :edit-model="''" :rules="rules" :form="form" :form-list="formOption">
        <div slot="promptLights" class="status-list">
          <div :class="color[form.statusLights]" class="prompt-lights" />
        </div>
        <template
          slot="completeDate"
          slot-scope="{
            data: {
              formItem: { disabled }
            }
          }"
        >
          <a-date-picker
            v-model="form.completeDate"
            :placeholder="disabled ? '' : '请选择'"
            :disabled-date="
              (current) => {
                return completeDateDisabled(current)
              }
            "
            :disabled="disabled"
          />
        </template>
        <template
          slot="delayTypes"
          slot-scope="{
            data: {
              formItem: { disabled }
            }
          }"
        >
          <a-tree-select v-model="form.delayTypes" placeholder="请选择逾期类别" :tree-data="delayTypeTree" :replace-fields="replaceFields" show-search multiple :disabled="disabled" :filter-tree-node="filterTreeNode" />
        </template>
      </custom-form>
      <template v-if="isOverdue">
        <titleName title="附件" />
        <UploadTableNew ref="uploadTable" :mode="file.mode" :init-file-list="file.fileList" :need-page="file.needPage" :use-add="source.type !== 'detail'" :use-delete="false" :business-code="file.businessCode" />
      </template>
      <template v-else>
        <titleName title="第三方完工确认单" />
        <UploadTableNew ref="uploadTable" :mode="file1.mode" :init-file-list="file1.fileList" :need-page="file1.needPage" :use-add="source.type !== 'detail'" :business-code="file1.businessCode" />
      </template>
    </a-card>
    <!-- 选择审批人 -->
    <selectApprover :business-id="businessId" :process-config="setProcessConfig" :is-close-upper="false" @closevisible="handleModalCancel(true)" />
    <!-- 选择审批人 -->
    <!-- 阶段/类别完成情况 -->
    <StageClassComple :visible.sync="stageClassCompleVisible" :isSetupComplete="isSetupComplete" @submit="lastSubmit" :rowName="rowName"></StageClassComple>
    <!-- 阶段/类别完成情况 -->
  </a-spin>
</template>
<script>
import { formOption, formOption1 } from '../model.js'
import weekPlanApi from '@/api/construction/weekPlanApi'
import StageClassComple from './stageClassComple'
export default {
  name: 'NodeCompletionView',
  components: {
    StageClassComple,
  },
  props: {
    // 节点完成数据
    source: {
      type: Object,
      default: () => {
        return {
          type: 'detail',
          data: {}
        }
      }
    },
    isAudit: {
      // 是否作为审批详情
      type: Boolean,
      default: false
    },
    loading: {
      // 加载
      type: Boolean,
      default: false
    },
    submiting: {
      // 提交
      type: Boolean,
      default: false
    },
    // 是否模态框模式
    useModal:{
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      // 表单对象
      form: {},
      // 附件
      file: {
        // 处理操作的模式：'add'模式下，删除操作会调用文件删除接口，'edit'模式只会在表格中移除删除数据，不会调用接口
        mode: 'add',
        // 上传文件的业务编码
        businessCode: 'PM49',
        // 是否需要分页
        needPage: false,
        // 初始化文件列表
        fileList: []
      },
      // 第三方完工确认单
      file1: {
        // 处理操作的模式：'add'模式下，删除操作会调用文件删除接口，'edit'模式只会在表格中移除删除数据，不会调用接口
        mode: 'add',
        // 上传文件的业务编码
        businessCode: 'PM50',
        // 是否需要分页
        needPage: false,
        // 初始化文件列表
        fileList: []
      },
      // 节点颜色
      color: {
        0: 'class-slider-0',
        1: 'class-slider-1',
        2: 'class-slider-2',
        3: 'class-slider-3',
        4: 'class-slider-4'
      },
      // 流程配置
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      // 业务id
      businessId: null,
      // 逾期类别树
      delayTypeTree: [],
      lastComplete:false, // 是否是最后一个节点
      lastCompleteObj:{}, // 是否是最后一个节点提交参数
      // 逾期类别树字段替换
      replaceFields: {
        children: 'children',
        title: 'title',
        key: 'value',
        value: 'value'
      },
      //阶段/类别完成情况
      stageClassCompleVisible:false,
      //是否设置完成情况
      isSetupComplete:false,
      rowName:null,
      // 是否逾期(审批时会默认不逾期，需要等待接口返回通过时间判断是否逾期)
      // isOverdue: this.isAudit ? false : [2, 4].includes(this.source.data?.statusLights)
    }
  },
  computed: {
    //是否逾期
    isOverdue() {
      return this.moment(this.form.completeDate).diff(this.moment(this.form.planEndTime), 'days') > 0
    },
    // 表单项
    formOption() {
      this.$checkRequireItem()
      const option = this.isOverdue ? this.$clone(formOption) : this.$clone(formOption1)
      return this.source.type === 'detail' || this.isAudit
        ? option.map((el) => {
            el.disabled = true
            return el
          })
        : option
    },
    // 表单校验
    rules() {
      const obj = {}
      this.formOption.forEach((item) => {
        if (item.rules) {
          obj[item.keyName] = item.rules
        }
      })
      return obj
    }
  },
  watch: {
    'form.laborResFee'() {
      this.computeRushFee()
    },
    'form.equipResFee'() {
      this.computeRushFee()
    },
    'form.materialResFee'() {
      this.computeRushFee()
    },
    'form.safetyMeasureFee'() {
      this.computeRushFee()
    }
  },
  mounted() {
    this.getDelayType()
    if (this.isAudit) {
      this.getData()
    }
  },
  async created() {
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('week_plan_node')
  },
  methods: {
    /**
     * @description: 格式化时间
     * @param {object/string} date 时间对象或字符串
     * @param {boolean} toMoment 是否转换为Moment
     * @return {object} moment时间格式
     */
    formatDate(date, toMoment = true) {
      if (date?._isAMomentObject) {
        return toMoment ? date : date.format('YYYY-MM-DD')
      } else {
        return toMoment ? this.moment(date) : date
      }
    },
    /**
     * @description: 计算预计赶工费用
     * @param {void}
     * @return {void}
     */
    computeRushFee() {
      // 解决浮点加法运算精度问题
      const { laborResFee, equipResFee, materialResFee, safetyMeasureFee } = this.form
      const arr = [laborResFee ?? 0, equipResFee ?? 0, materialResFee ?? 0, safetyMeasureFee ?? 0]
      let l = []
      arr.forEach((el) => {
        l.push(el.toString().split('.')[1]?.length || 0)
      })
      const lng = Math.max(...l)
      let num = 0
      arr.forEach((el) => {
        num += el * Math.pow(10, lng)
      })
      this.form.rushFee = num / Math.pow(10, lng)
    },
    /**
     * @description: 获取逾期类型
     * @param {void}
     * @return {void}
     */
    getDelayType() {
      weekPlanApi.labelTreeList({ pageNo: 1, pageSize: 1000, type: 11 }).then(({ code, data }) => {
        if (code === 200) {
          this.delayTypeTree = data
        }
      })
    },
    /**
     * @description: 获取节点维护信息
     * @param {void}
     * @return {void}
     */
    getData() {
      this.$emit('update:loading', true)
      weekPlanApi
        .workWithResult(this.isAudit ? this.$route.query.businessId : this.source.data?.id)
        .then(({ code, data }) => {
          const {
            projectName,
            businessMatters,
            phaseCategory,
            controlLevelName,
            period,
            planStartTime,
            planEndTime,
            statusLights,
            nodeStatusName,
            verifyFiles,
            completeStandard,
            firstResName,
            directResPerList,
            nodeResultVO,
            lastComplete
          } = data
         
          if (code === 200) {
            console.log(nodeResultVO,2222222)
            this.lastComplete = lastComplete;
            this.businessId = this.isAudit ? null : this.source.data?.id
            let form = {
              projectName,
              businessMatters,
              phaseCategory,
              controlLevelName,
              period,
              planStartTime,
              planEndTime,
              statusLights,
              nodeStatusName,
              completeDate: nodeResultVO?.completeDate || '',
              verifyFiles,
              completeStandard,
              firstResName,
              directResPerList: directResPerList.map((el) => el.label).join(','),
              delayReason: nodeResultVO?.delayReason,
              creatorName: data?.completeCreateName ?? JSON.parse(sessionStorage.getItem('ycloud-user_info')).name,
              createTime: nodeResultVO?.createTime ? this.moment(nodeResultVO?.createTime).format('YYYY-MM-DD') : this.moment().format('YYYY-MM-DD')
            }
            this.form = form
            this.rowName = this.source?.rowName;
            if (this.isOverdue) {
              // 逾期
              form = {
                ...form,
                delayTypes: nodeResultVO?.delayTypes,
                laborResFee: nodeResultVO?.laborResFee,
                equipResFee: nodeResultVO?.equipResFee,
                materialResFee: nodeResultVO?.materialResFee,
                safetyMeasureFee: nodeResultVO?.safetyMeasureFee,
                rushFee: nodeResultVO?.rushFee,
                laborRes: nodeResultVO?.laborRes,
                equipRes: nodeResultVO?.equipRes,
                materialRes: nodeResultVO?.materialRes,
                safetyMeasure: nodeResultVO?.safetyMeasure
              }
              this.file.fileList = (nodeResultVO?.resultFileVO || []).map((el) => {
                el.useDelete = this.source.type !== 'detail'
                return el
              })
            } else {
              // 未逾期
              this.file1.fileList = (nodeResultVO?.resultThirdFileVO || []).map((el) => {
                el.useDelete = this.source.type !== 'detail'
                return el
              })
            }
            this.form = form
            // 实际完成时间是否禁用
            // 是否查看
            if (this.source.type === 'detail') {
              this.useCompleteDate = true
            } else {
              this.useCompleteDate = false
            }
          }
        })
        .finally(() => {
          this.$emit('update:loading', false)
        })
    },
    /**
     * @description: 提交审批
     * @param {void}
     * @return {void}
     */
    handleSubmit() {
      const vm = this
      vm.$refs.form.validate((valid) => {
        if (valid) {
          if (!vm.isOverdue) {
            if (vm.file1.fileList.length < 1) {
              vm.$message.warning('请先上传第三方完工确认单附件！')
              return
            }
          }
          vm.setProcessConfig = null
          vm.submitApprovalConfirm(vm.processConfig, (flag) => {
            if (!flag) return
            const { completeDate, delayReason, laborResFee, equipResFee, materialResFee, safetyMeasureFee, rushFee, laborRes, equipRes, materialRes, safetyMeasure, delayTypes } = vm.form
            let params = {
              workId: vm.source.data?.id,
              completeDate: vm.formatDate(completeDate, false),
              delayReason
            }
            if (vm.isOverdue) {
              // 逾期
              params = {
                ...params,
                laborResFee,
                equipResFee,
                materialResFee,
                safetyMeasureFee,
                rushFee,
                laborRes,
                equipRes,
                materialRes,
                safetyMeasure,
                delayTypes,
                otherInfoList: vm.file.fileList
              }
            } else {
              // 未逾期
              params.thirdInfoList = vm.file1.fileList
            }
            if(this.lastComplete){
              this.stageClassCompleVisible= true;
              this.isSetupComplete = false;
              this.lastCompleteObj = params;
            }else{
              this.submit(params)
            }
          })
        }
      })
    },
    // 最后一个节点点击提交
    lastSubmit(data,flag){
      if(!flag){
        return
      }
      this.lastCompleteObj.completeStatus = data.completeStatus;
      this.submit(this.lastCompleteObj)
    },
        /**
       提交接口
     */
     submit(params,data){
      const vm = this
      vm.$emit('update:submiting', true)
      weekPlanApi
              .nodeMaintain(params)
              .then(({ code, data }) => {
                if (code === vm.SUCCESS_CODE) {
                  // 设置businessId触发审批人弹框
                  vm.businessId = data.id
                  vm.$message.success('提交成功！')
                  vm.setProcessConfig = vm.processConfig
                  // 不选择审批人时二次弹框手动关闭
                  if (parseInt(vm.setProcessConfig) === 4) {
                     vm.handleModalCancel(true)
                  }
                }
              })
              .finally(() => {
                vm.$emit('update:submiting', false)
              })
     },
    /**
     * @description: 时间完成时间禁用
     * @param {object} current 当前时间对象
     * @return {boolean}
     */
    completeDateDisabled(current) {
      return current && current > this.moment().endOf('day')
    },
    /**
     * @description: 下拉树形框搜索过滤
     * @param {string} input 输入值
     * @param {object} option 下拉对象
     * @return {boolean} 是否符合过滤条件
     */
    filterTreeNode(input, treeNode) {
      return treeNode.componentOptions.propsData.title.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    /**
     * @description: 关闭
     * @return {void}
     */
    handleclose() {
      this.form = {}
      this.file.fileList = []
      this.file1.fileList = []
    },
    /**
     * @description: 关闭模态框
     * @param {boolean} 是否需要刷新
     * @return {void}
     */
    handleModalCancel(refresh = false) {
      this.handleclose()
      this.$emit('handleModalCancel', refresh)
    }
  }
}
</script>
<style lang="less" scoped>
.status-list {
  display: flex;
  align-items: center;
  margin-top: 7px;
}
.prompt-lights {
  width: 59px;
  height: 23px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.modal{
  border: none;
  box-shadow: none;
  margin: 0;
}
</style>
